//
//  MeishiListViewController.m
//  B段项目
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 徐茂怀. All rights reserved.
//

#import "MeishiListViewController.h"
#import "UIImageView+WebCache.h"
#import "NSXFirstPageListModel.h"
#import "NSXFirstPageListTableViewCell.h"
#import "FitHeader.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "BKZoomView.h"
#import "NSXLeftShakeViewController.h"
#import "NSXFirstPageWEBViewController.h"
//数据解析
#import "XMHNetWorkongMethods.h"
@interface MeishiListViewController ()<UITableViewDataSource , UITableViewDelegate , UIPickerViewDataSource , UIPickerViewDelegate>
@property(nonatomic , retain)UITableView *tableView;
@property(nonatomic , retain)NSMutableArray *dataSourceArray;
@property(nonatomic , assign)NSInteger page;
@property(nonatomic , retain)NSDictionary *dataDic;
@property(nonatomic , retain)MBProgressHUD *progressView;
@property(nonatomic , retain)NSMutableArray *changePageArray;
@property(nonatomic , retain)UIPickerView *pickView;
@property(nonatomic , retain)BKZoomView *zoomView;
//灰色View上的白色View
@property(nonatomic , retain)UIView *changePageView;
//点击背景的灰色View
@property(nonatomic , retain)UIView *grayColorView;
@property(nonatomic,assign)NSInteger flag;
@property(nonatomic, strong)UIAlertController *alertController;
@property(nonatomic, strong)UIAlertView *alertView;
@end

@implementation MeishiListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"美食列表";
    _changePageArray = [NSMutableArray array];
    self.dataSourceArray = [NSMutableArray array];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
    //右侧选择器
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-hand"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
    
    //左侧摇一摇
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"摇一摇.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    
    //修改button颜色
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //加载菊花
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    _progressView.labelText = @"请稍等...";
    [_progressView setMode:MBProgressHUDModeIndeterminate];
    [_progressView show:YES];
    _progressView.backgroundColor = [UIColor colorWithRed:0.58 green:0.6 blue:0.61 alpha:0.3];
    [self.view addSubview:_progressView];
    
    _page = 1;
    [self getData];
#pragma mark 下拉刷新..上来加载
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString *path = [str stringByAppendingPathComponent:@"1"];
        NSFileManager *manager = [NSFileManager defaultManager];
        [manager removeItemAtPath:path error:nil];
        //清空原来的数据
        [_dataSourceArray removeAllObjects];
        //蒋页码重新置为1
        _page = 1;
        //获取网络数据
        [self getData];
    }];
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //页码加1
        _page++;
        [self getData];
    }];
}

-(void)loadView
{
    [super loadView];
    _flag = 0;
#pragma mark  tableView部分
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    //去掉cell的线
    _tableView.separatorStyle = 0;
    [self.view addSubview:_tableView];
}

#pragma mark tableViewCell部分
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    NSXFirstPageListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[NSXFirstPageListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    //取消点击效果
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if (_dataSourceArray.count != 0)
    {
        cell.NSXFirstModel = self.dataSourceArray[indexPath.row];
        if ([_dataSourceArray[indexPath.row]category].length == 0)
        {
            cell.categoryLabel.text = @"";
        }
        if ([_dataSourceArray[indexPath.row]age].length == 0)
        {
            cell.ageLabel.text = @"";
        }
        if ([_dataSourceArray[indexPath.row]effect1].length == 0)
        {
            cell.effectLabel.text = @"";
        }
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100 *FitWidth;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataSourceArray.count) {
        self.hidesBottomBarWhenPushed = YES;
        NSXFirstPageWEBViewController *WVC = [[NSXFirstPageWEBViewController alloc]init];
        WVC.idString = [_dataSourceArray[indexPath.row] ID];
        WVC.modelString = [_dataSourceArray[indexPath.row]title];
        WVC.NSXModel = _dataSourceArray[indexPath.row];
        [self.navigationController pushViewController:WVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    }
    else
    {
        
    }
    
}

#pragma mark 数据解析
-(void)getData
{
    NSString *page = [NSString stringWithFormat:@"%ld",_page];
    NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *path = [str stringByAppendingPathComponent:page];
    if ([NSDictionary dictionaryWithContentsOfFile:path]) {
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
        NSArray *array = [dic objectForKey:@"results"];
        for (NSDictionary *dic in array)
        {
            NSXFirstPageListModel *model = [[NSXFirstPageListModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataSourceArray addObject:model];
        }
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_progressView removeFromSuperview];
        [_tableView reloadData];
        
    }
    else
    {
        NSString *string1 = @"http://ibaby.ipadown.com/api/food/food.show.list.php?category=%E7%83%98%E7%84%99&p=";
        NSString *string2 = @"&pagesize=12";
        NSString *urlString = [NSString stringWithFormat:@"%@%ld%@" , string1 , _page , string2];
        [XMHNetWorkongMethods getDataVyString:urlString BodyString:nil WithDataBlock:^(id data) {
            if (_page == 1) {
                NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
                NSString *path = [str stringByAppendingPathComponent:@"1"];
                NSFileManager *manager = [NSFileManager defaultManager];
                [manager createFileAtPath:path contents:data attributes:nil];
            }
            
            NSArray *array = [data objectForKey:@"results"];
            for (NSDictionary *dic in array)
            {
                NSXFirstPageListModel *model = [[NSXFirstPageListModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [_dataSourceArray addObject:model];
            }
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshing];
            [_progressView removeFromSuperview];
            [_tableView reloadData];
        } WithFailure:^(NSError *error) {
            if (!_dataSourceArray.count) {
                _alertController = [UIAlertController alertControllerWithTitle:@"网络错误" message:@"请检查网络" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:_alertController animated:YES completion:nil];
                UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [_alertController removeFromParentViewController];
                    [_progressView removeFromSuperview];
                    [_tableView.header endRefreshing];
                }];
                UIAlertAction *going = [UIAlertAction actionWithTitle:@"继续加载" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self getData];
                    [_alertController removeFromParentViewController];
                }];
                [_alertController addAction:going];
                [_alertController addAction:ok];
            }
            
        }];
        
    }
}


#pragma mark  导航条右侧button的点击方法
-(void)rightButtonAction
{
    if (_flag == 0) {
        //底层灰色的View
        _grayColorView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49)];
        _grayColorView.backgroundColor = [UIColor grayColor];
        _grayColorView.alpha = 0.5;
        [self.view addSubview:_grayColorView];
        
        //白色的View
        _changePageView = [[UIView alloc]initWithFrame:CGRectMake(30 *FitWidth, 100 *FitHeight, 315 *FitWidth, 300 *FitHeight)];
        _changePageView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        [self.view addSubview:_changePageView];
        
        //pickview
        _pickView = [[UIPickerView alloc]initWithFrame:CGRectMake(20 *FitWidth, 20 *FitHeight, 275 *FitWidth, 240 *FitHeight)];
        _pickView.dataSource = self;
        _pickView.delegate = self;
        _pickView.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
        //pickView赋值的数组
        for (NSInteger i = 1; i < 179; i++) {
            NSString *s = [NSString stringWithFormat:@"第%ld页",i];
            [_changePageArray addObject:s];
        }
        [_pickView selectRow:_page - 1 inComponent:0 animated:NO];
        [_changePageView addSubview:_pickView];
        
        //取消按钮
        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        cancelButton.titleLabel.font = [UIFont systemFontOfSize:18 * FitWidth];
        cancelButton.frame = CGRectMake(20 *FitWidth, 265 *FitHeight, 70 *FitWidth, 30 *FitHeight);
        [cancelButton addTarget:self action:@selector(cancelButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_changePageView addSubview:cancelButton];
        
        //确定按钮
        UIButton *certainButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [certainButton setTitle:@"确定" forState:UIControlStateNormal];
        certainButton.titleLabel.font = [UIFont systemFontOfSize:18 * FitWidth];
        certainButton.frame = CGRectMake(225 *FitWidth, 265 *FitHeight, 70 *FitWidth, 30 *FitHeight);
        [certainButton addTarget:self action:@selector(certainButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_changePageView addSubview:certainButton];
        _flag = 1;
    }
    else
    {
        [_grayColorView removeFromSuperview];
        [_changePageView removeFromSuperview];
        _flag = 0;
    }
}

//跳转到'摇一摇'页面
-(void)leftButtonAction
{
    NSXLeftShakeViewController *LVC = [[NSXLeftShakeViewController alloc]init];
    [self.navigationController pushViewController:LVC animated:YES];
}

#pragma mark  取消/确定的点击方法
-(void)cancelButtonAction
{
    //移除view
    [_grayColorView removeFromSuperview];
    [_changePageView removeFromSuperview];
}
-(void)certainButtonAction
{
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    _progressView.labelText = @"请稍等...";
    [_progressView setMode:MBProgressHUDModeIndeterminate];
    [_progressView show:YES];
    _progressView.backgroundColor = [UIColor colorWithRed:0.58 green:0.6 blue:0.61 alpha:0.3];
    [self.view addSubview:_progressView];
    [_grayColorView removeFromSuperview];
    [_changePageView removeFromSuperview];
    //移除盖在上面的页面
    [_dataSourceArray removeAllObjects];
    [self getData];
    [_tableView reloadData];
    _flag = 0;
}


#pragma mark 选择器设置部分
//一个分组
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//个数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _changePageArray.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [_changePageArray objectAtIndex:row];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //截取字符串中的数字
    NSString *ss =[_changePageArray objectAtIndex:row];
    NSString *s = [ss substringFromIndex:1];
    NSInteger i = s.length - 1;
    NSString *aa = [s substringWithRange:NSMakeRange(0, i)];
    NSInteger sum = [aa integerValue];
    _page = sum;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
